package com.ruoyi.web.controller.module;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.OkHttpClientUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.AdBanner;
import com.ruoyi.system.service.module.IAdBannerService;
import com.ruoyi.system.service.system.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 轮播图（广告）Controller
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Validated
@Api(value = "轮播图（广告）控制器", tags = {"轮播图（广告）管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/banner")
public class AdBannerController extends BaseController {

    private final IAdBannerService adBannerService;
    private final ISysDictDataService sysDictDataService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;
//
	@Value("${ruoyi.apiUrl}")
	private String apiUrl;

    /**
     * 查询轮播图（广告）列表
     */
    @ApiOperation("查询轮播图（广告）列表")
    @PreAuthorize("@ss.hasPermi('module:banner:list')")
    @GetMapping("/list")
    public TableDataInfo<AdBanner> list(@Validated AdBanner adBanner) {
		QueryWrapper<AdBanner> qw = new QueryWrapper<>();
		if(ObjectUtil.isNotEmpty(adBanner.getAdType())){
			qw.eq("ad_type",adBanner.getAdType());
		}
        if (ObjectUtil.isNotEmpty(adBanner.getMerId())){
            qw.eq("mer_id",adBanner.getMerId());
        }
		qw.orderByAsc("sort");
        TableDataInfo<AdBanner> td = PageUtils.buildDataInfo(adBannerService.page(PageUtils.buildPage(),qw));
        List<AdBanner> list = td.getRows();
        list.forEach(banner->{
//            if(banner.getAdType() != null){
//                banner.setAdTypeName(sysDictDataService.selectDictLabel("banner_type",banner.getAdType().toString()));
//            }

			if(StrUtil.isNotEmpty(banner.getImgUrl())){
				banner.setImgPath(imgUrl + banner.getImgUrl());
			}

            if(StrUtil.isNotEmpty(banner.getLinkType())){
                banner.setLinkTypeName(sysDictDataService.selectDictLabel("link_type",banner.getLinkType()));
            }
        });
        return td;
    }

    /**
     * 获取轮播图（广告）详细信息
     */
    @ApiOperation("获取轮播图（广告）详细信息")
    @PreAuthorize("@ss.hasPermi('module:banner:query')")
    @GetMapping("/{id}")
    public AjaxResult<AdBanner> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
		AdBanner banner = adBannerService.getById(id);
		if(banner != null) {
			if(StrUtil.isNotEmpty(banner.getImgUrl())){
				banner.setImgPath(imgUrl + banner.getImgUrl());
			}
		}
		return AjaxResult.success(banner);
    }

    /**
     * 新增轮播图（广告）
     */
    @ApiOperation("新增轮播图（广告）")
    @PreAuthorize("@ss.hasPermi('module:banner:add')")
    @Log(title = "轮播图（广告）", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated @RequestBody AdBanner adBanner) {
    	boolean bl = adBannerService.save(adBanner);
    	if(bl){
			OkHttpClientUtil.getInstance().getData( apiUrl + "redis/reset/banner/" + adBanner.getAdType());
		}
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 修改轮播图（广告）
     */
    @ApiOperation("修改轮播图（广告）")
    @PreAuthorize("@ss.hasPermi('module:banner:edit')")
    @Log(title = "轮播图（广告）", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated @RequestBody AdBanner adBanner) {
		boolean bl = adBannerService.updateById(adBanner);
		if(bl){
			OkHttpClientUtil.getInstance().getData(apiUrl + "redis/reset/banner/" + adBanner.getAdType());
		}
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 删除轮播图（广告）
     */
    @ApiOperation("删除轮播图（广告）")
    @PreAuthorize("@ss.hasPermi('module:banner:remove')")
    @Log(title = "轮播图（广告）" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(adBannerService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
